#include "preHeader.h"
#include "Spell.h"
#include "SpellEffects.h"
#include "Map/MapInstance.h"

GErrorCode SpellEffects::CanCast4Mine(Unit* pCaster,
	LocatableObject* pTarget, const SpellPrototype* pSpellProto,
	uint32 spellLevel, size_t effectIndex)
{
	if (!pCaster->IsType(TYPE_PLAYER)) {
		return ErrSpellInvalidCaster;
	}
	if (pTarget == NULL || !pTarget->IsType(TYPE_STATICOBJECT)) {
		return ErrSpellInvalidTarget;
	}

	auto pPlayer = static_cast<Player*>(pCaster);
	auto pSObj = static_cast<StaticObject*>(pTarget);
	auto errCode = pSObj->CanMine(pPlayer);
	if (errCode != CommonSuccess) {
		return errCode;
	}

	return CommonSuccess;
}

uint32 SpellEffects::GetCastStageExtraTime4Mine(
	const Spell* pSpell, SpellStageType stage, size_t effectIndex)
{
	switch (stage) {
		case SpellStageType::Chant: {
			auto pSObj = GetMineTarget(pSpell);
			return pSObj != NULL ? pSObj->GetProto()->mineAnimTime : 0;
		}
		default: {
			return 0;
		}
	}
}

void SpellEffects::Start4Mine(Spell* pSpell, size_t effectIndex)
{
	auto pPlayer = static_cast<Player*>(pSpell->GetCaster());
	auto pSObj = pPlayer->GetMapInstance()->
		GetStaticObject(pSpell->GetTargetGuid());
	if (pSObj != NULL) {
		pSObj->StartMine(pPlayer, pSpell, effectIndex);
	}
}

void SpellEffects::Stop4Mine(Spell* pSpell, size_t effectIndex)
{
	auto pPlayer = static_cast<Player*>(pSpell->GetCaster());
	auto pSObj = pPlayer->GetMapInstance()->
		GetStaticObject(pSpell->GetTargetGuid());
	if (pSObj != NULL) {
		pSObj->StopMine(pPlayer, pSpell, effectIndex);
	}
}

void SpellEffects::Apply4Mine(
	Spell* pSpell, Player* pTarget, size_t effectIndex)
{
	auto pSObj = pTarget->GetMapInstance()->
		GetStaticObject(pSpell->GetTargetGuid());
	if (pSObj != NULL) {
		pSObj->FinishMine(pTarget, pSpell, effectIndex);
	}
}

StaticObject* SpellEffects::GetMineTarget(const Spell* pSpell)
{
	auto pPlayer = static_cast<Player*>(pSpell->GetCaster());
	return pPlayer->GetMapInstance()->
		GetStaticObject(pSpell->GetTargetGuid());
}
